//
//  MyBitMouseView.m
//  MyBitMouse
//
//  Created by 高明阳 on 2021/3/12.
//

#import "MyBitMouseView.h"
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
/// default 7
static const NSUInteger row_count = 3;
@interface MyBitMouseView()
{
    UIImageView *_imageV;
    UIButton *_button;
    NSTimer *_timer;
}
@property (nonatomic,strong)UIImageView *backgroundImageView;
@property (nonatomic,assign)NSUInteger bitMouseScore;
@property (nonatomic,strong)UIImageView *assistView;

@property (nonatomic,strong)UIPanGestureRecognizer *panGesture;

@property (nonatomic,strong)NSMutableArray *subImageViewsArray;
@end

@implementation MyBitMouseView

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self initBitMouseViews];
        [self addMySubViews];
        [self addMyContraints];
    }
    return self;
}

-(void)addMySubViews{
    [self addSubview:self.assistView];
}
-(void)addMyContraints{
    self.assistView.frame = CGRectMake(10, 100, 64, 64);
}

-(void)move:(UIPanGestureRecognizer *)sender{
//    NSLog(@" 进入到move 函数 ");
    if (sender.state == UIGestureRecognizerStateChanged || sender.state == UIGestureRecognizerStateEnded ) {
        CGPoint translation = [sender translationInView:sender.view];
//        CGPoint locationPoint = [sender locationInView:sender.view];
//        NSLog(@"locationPoint:%@",NSStringFromCGPoint(locationPoint));
        CGPoint assistViewCenter = self.assistView.center;
        CGFloat  newX = assistViewCenter.x + translation.x;
        CGFloat newY = assistViewCenter.y + translation.y;
        if (newX < self.assistView.bounds.size.width/2) {
            newX = self.assistView.bounds.size.width/2;
        }
        if (newX > SCREEN_WIDTH - self.assistView.bounds.size.width/2) {
            newX = SCREEN_WIDTH - self.assistView.bounds.size.width/2;
        }
        if(newY < self.assistView.bounds.size.height/2){
            newY = self.assistView.bounds.size.height/2;
        }
        
        if (newY > SCREEN_HEIGHT - self.assistView.bounds.size.height/2) {
            newY = SCREEN_HEIGHT - self.assistView.bounds.size.height/2;
        }
        assistViewCenter = CGPointMake(newX, newY);
        self.assistView.center = assistViewCenter;
        [sender setTranslation:CGPointZero inView:sender.view];
        NSLog(@"assistViewFrame:%@",NSStringFromCGRect(self.assistView.frame));
        //检查和地鼠view是否有碰撞
        for (int i=0; i<self.subImageViewsArray.count; i++) {
            Boolean isMutul = [self checkIsOverlapView1:self.assistView andView2:self.subImageViewsArray[i]];
            if (isMutul) {
                NSLog(@"碰撞索引 i:%d",i);
                [self hitWithImageView:self.subImageViewsArray[i]];
            }
        }
    }
}
-(Boolean)checkIsOverlapView1:(UIView *)viewOne andView2:(UIView *)viewTwo{
    Boolean isMutul =CGRectIntersectsRect(viewOne.frame,viewTwo.frame);
    return isMutul;
}
-(void)initBitMouseViews{
    //创建底层显示的背景图片
        CGFloat width = (SCREEN_WIDTH - (row_count+1)*20)/row_count;
        NSLog(@"SCREEN_WIDTH :%f",SCREEN_WIDTH);
        NSLog(@"width :%f",width);
        for (int i = 0; i < row_count; i++) {
            for (int j = 0; j < row_count; j++) {
                //添加地鼠洞的图片
                _imageV = [[UIImageView alloc] initWithFrame:CGRectMake(20+20*i+width*i, 250+width*j, width, width)];
                _imageV.image = [UIImage imageNamed:@"emptyhole.png"];
                _imageV.tag = 149+i*row_count+j+1;
                //创建每个洞的点击事件
               _button = [UIButton buttonWithType:UIButtonTypeSystem];
                _button.frame = CGRectMake(0, 0, width, width);
                [_button addTarget:self action:@selector(hit:) forControlEvents:UIControlEventTouchUpInside];
                //给每个button添加tag值来确定你点击的是那个button
                _button.tag = 100+i*row_count+j+1;
                [_imageV addSubview:_button];
                _imageV.userInteractionEnabled = YES;
                [self.backgroundImageView addSubview:_imageV];
                [self.subImageViewsArray addObject:_imageV];
            }
        }
        [self addSubview:self.backgroundImageView];
        [self addTimer];
}
- (void)addTimer
{
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(startGame) userInfo:nil repeats:YES];
}

//启动地鼠出洞的动画
- (void)startGame
{
    //定义一个可变数组来存放播放的图片
    NSMutableArray *arr = [NSMutableArray array];
    //地鼠出洞的图片
    for (int i = 1; i < 7; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"t%d.png",i]];
        [arr addObject:image];
    }
    //地鼠回洞的图片
    for (int i = 1; i < 7; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"t%d.png",7-i]];
        [arr addObject:image];
    }
    //获取随机值来让地鼠在随机位置出现
    NSInteger num = arc4random()%(row_count*row_count)+150;
    //根据tag值来获取随机的现实地鼠图片的imageView
    _imageV = (UIImageView *)[self viewWithTag:num];
    //指定imageView的不妨图片的数组
    _imageV.animationImages = arr;
    //指定播放次数
    _imageV.animationRepeatCount = 1;
    //指定播放时间
    _imageV.animationDuration = 1;
    //开启播放
    [_imageV startAnimating];
}

- (void)hit:(UIButton *)sender
{
    //根据点击button的tag值来获取当前的imageV
    NSInteger num = sender.tag;
    //根据button的tag值来获取当前点击的是那个imageview
    _imageV = (UIImageView *)[self viewWithTag:num+49];
    //确定是哪个位置的button来执行点击事件
    _button = (UIButton *)[self viewWithTag:num];
    //判断当前点击的imageView是否在播放动画
    [self hitWithImageView:_imageV];
//    if (_imageV.isAnimating == YES) {
//        NSLog(@"打到了地鼠");
//        //停止播放动画
//        [_imageV stopAnimating];
//        [self hitMouseAnimationWithImageView:_imageV];
//    }else{
//       //如果点击的位置没有在播放动画执行的方法.
//        NSLog(@"没打到了地鼠");
//    }
}

-(void)hitWithImageView:(UIImageView *)image{
    if (image.isAnimating == YES) {
        NSLog(@"打到了地鼠");
        //停止播放动画
        [image stopAnimating];
        [self hitMouseAnimationWithImageView:image];
    }else{
       //如果点击的位置没有在播放动画执行的方法.
        NSLog(@"没打到了地鼠");
    }
}

-(void)hitMouseAnimationWithImageView:(UIImageView *)imageView{
    self.bitMouseScore++;
    if (self.delegate && [self.delegate respondsToSelector:@selector(bitMouseScore:)]) {
        [self.delegate bitMouseScore:self.bitMouseScore];
    }
    //定义一个可变数组来存储地鼠被击打时的图片
    NSMutableArray *imageArr = [NSMutableArray array];
    //地鼠被击打的图片
    UIImage *image = [UIImage imageNamed:@"hit.png"];
    //空洞的图片
    UIImage *image1 = [UIImage imageNamed:@"emptyhole.png"];
    //讲两张图片添加到可变数组中
    [imageArr addObject:image];
    [imageArr addObject:image1];
    UIImageView *hitImgV = [[UIImageView alloc] initWithFrame:imageView.frame];
    [self addSubview:hitImgV];
    NSUInteger animationDuration = 1;
    //指定播放动画的数组
    hitImgV.animationImages = imageArr;
    //制动播放的次数(0为无限循环播放)
    hitImgV.animationRepeatCount = 1;
    //指定播放的时间
    hitImgV.animationDuration = animationDuration;
    //开始播放动画
    [hitImgV startAnimating];
    [self performSelector:@selector(finishHitAnimation:) withObject:hitImgV afterDelay:animationDuration];
//    [self performSelector:@selector(finishHitAnimation:) withObject:hitImgV];
}

-(void)finishHitAnimation:(UIImageView *)hitImageV{
    [hitImageV removeFromSuperview];
}

#pragma mark -- lazy load
- (UIImageView *)backgroundImageView{
    if (_backgroundImageView == nil) {
        _backgroundImageView = [[UIImageView alloc] initWithFrame:self.frame];
        _backgroundImageView.image = [UIImage imageNamed:@"back.png"];
        //打开图片的交互(imageView默认是关闭的)
        _backgroundImageView.userInteractionEnabled = YES;
    }
    return _backgroundImageView;
}
- (UIImageView *)assistView{
    if (_assistView == nil) {
        _assistView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"assistBtn"]];
        _assistView.userInteractionEnabled = YES;
        [_assistView addGestureRecognizer:self.panGesture];
    }
    return _assistView;
}
- (UIPanGestureRecognizer *)panGesture{
    if (_panGesture == nil) {
        _panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];
//        _panGesture.delegate = self;

    }
    return _panGesture;
}
- (NSMutableArray *)subImageViewsArray{
    if (_subImageViewsArray == nil) {
        _subImageViewsArray = [NSMutableArray new];
    }
    return _subImageViewsArray;
}
@end
